# -*- coding: utf-8 -*-
import json
from uuid import uuid4
from flask import current_app as app
from app.db.models.users import Token
from app.db.models.packages import Packages
from app.db.models.meta_limit import TypeLimitTotal5, TypePeriodTotal5, TypeDuration, TypeFreqTotal100000

CONTENT_TYPE = "application/json"

admin_client = app.test_client()
admin_client.set_cookie("localhost", "token", Token.objects.filter({}).first().token)


def create_plan():
    limit5 = TypeLimitTotal5().to_mongo().to_dict()
    period5 = TypePeriodTotal5().to_mongo().to_dict()
    freq100000 = TypeFreqTotal100000().to_mongo().to_dict()
    data = {
        "key": "scanv_basic",
        "name": "专业版",
        "marks": "专业版-测试用例",
        "chargeType": "plan",
        "limit": {
            "domain": {**limit5},
            "smsAlert": {**period5},
            "emailAlert": {**period5},
            "maxPage": {**freq100000},
            "alertGroup": {**limit5},
            "alertReceiver": {**limit5},
            "aviliableMaxHistory": TypeDuration(total=60).to_mongo().to_dict(),
            "sitePortrait": {**limit5},
            "assetManualTask": {**period5},
            "vulManualTask": {**period5},
            "vulMaxFreq": {**freq100000},
            "vulMaxDepth": {**period5},
            "vulMaxPage": {**freq100000},
            "sslManualTask": {**period5},
            "sslMaxFreq": {**freq100000},
            "securityEventManualTask": {**period5},
            "securityEventMaxFreq": {**freq100000},
            "securityEventMaxDepth": {**period5},
            "securityEventMaxPage": {**freq100000},
            "contentManualTask": {**period5},
            "contentMaxFreq": {**freq100000},
            "contentMaxDepth": {**period5},
            "contentMaxPage": {**freq100000},
            "ipv6ManualTask": {**period5},
            "httpMaxTask": {**limit5},
            "httpMaxTaskEnable": {**limit5},
            "pingMaxTask": {**limit5},
            "pingMaxTaskEnable": {**limit5},
        }
    }
    admin_client.post("/api/v2/packages/template/add", data=json.dumps(data), content_type=CONTENT_TYPE)


def clean_plan():
    Packages.objects.filter(key="scanv_basic").delete()


def create_user(username):
    from app.handler.v2_users import LoginHelper
    user = LoginHelper.create_user(username)
    return user


def clean_user(username):
    from app.db.models.users import User
    from app.db.models.balances import Balances
    user = User.objects.filter(username=username).first()
    Balances.objects.filter(uid=user.id).delete()
    User.objects.filter(id=user.id).delete()


def mock_scanner_action(url, body):
    if url == "/v1/tasks:create":
        return {"task_id": uuid4().hex}
    elif url == "/v1/tasks:modify":
        return {"code": 5}
    elif url in ["/v1/tasks:remove", "/v1/tasks:rescan", "/v1/tasks:batchRemove"]:
        return
